import 'dart:convert';

import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';

import '../models/user.dart';

class AuthService {
  // 使用本地测试地址
  static const String _baseUrl = 'http://127.0.0.1:3000/api'; // 修改端口号为 3000
  static const String _tokenKey = 'auth_token';
  static const String _userKey = 'user_data';

  // 默认管理员账号
  static const String _defaultAdminUsername = '123455';
  static const String _defaultAdminPassword = '123455';
  static const String _defaultAdminEmail = 'admin@example.com';

  // 默认普通用户账号
  static const String _defaultUserUsername = 'user123';
  static const String _defaultUserPassword = 'user123';
  static const String _defaultUserEmail = 'user@example.com';

  final SharedPreferences _prefs;
  String? _token;
  User? _currentUser;

  AuthService(this._prefs) {
    _token = _prefs.getString(_tokenKey);
    final userJson = _prefs.getString(_userKey);
    if (userJson != null) {
      _currentUser = User.fromJson(jsonDecode(userJson));
    }
  }

  String? get token => _token;
  User? get currentUser => _currentUser;
  User? get user => _currentUser;

  Future<bool> loadUser() async {
    if (_token == null) return false;

    try {
      print('尝试加载用户信息: $_baseUrl/users/me');
      final response = await http.get(
        Uri.parse('$_baseUrl/users/me'),
        headers: {
          'Content-Type': 'application/json',
          'Authorization': 'Bearer $_token',
        },
      );

      print('加载用户信息响应状态码: ${response.statusCode}');
      print('加载用户信息响应内容: ${response.body}');

      if (response.statusCode == 200) {
        final data = jsonDecode(response.body);
        _currentUser = User.fromJson(data);
        await _prefs.setString(_userKey, jsonEncode(data));
        return true;
      }
      return false;
    } catch (e) {
      print('加载用户信息失败: $e');
      return false;
    }
  }

  Future<bool> login(String username, String password) async {
    try {
      print('尝试登录: $username');
      print('登录 URL: $_baseUrl/login');

      // 使用默认管理员账号登录
      if (username == _defaultAdminUsername && password == _defaultAdminPassword) {
        print('使用默认管理员账号登录');
        _token = 'admin_token';
        _currentUser = User(
          id: 'admin',
          username: _defaultAdminUsername,
          email: _defaultAdminEmail,
          role: 'admin',
        );
        await _prefs.setString(_tokenKey, _token!);
        await _prefs.setString(_userKey, jsonEncode(_currentUser!.toJson()));
        return true;
      }

      // 使用默认普通用户账号登录
      if (username == _defaultUserUsername && password == _defaultUserPassword) {
        print('使用默认普通用户账号登录');
        _token = 'user_token';
        _currentUser = User(
          id: 'user',
          username: _defaultUserUsername,
          email: _defaultUserEmail,
          role: 'user',
        );
        await _prefs.setString(_tokenKey, _token!);
        await _prefs.setString(_userKey, jsonEncode(_currentUser!.toJson()));
        return true;
      }

      final requestBody = {
        'username': username,
        'password': password,
      };

      print('发送登录请求体: ${jsonEncode(requestBody)}');

      try {
        final response = await http
            .post(
              Uri.parse('$_baseUrl/login'),
              headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json',
              },
              body: jsonEncode(requestBody),
            )
            .timeout(const Duration(seconds: 5));

        print('登录响应状态码: ${response.statusCode}');
        print('登录响应头: ${response.headers}');
        print('登录响应内容: ${response.body}');

        if (response.statusCode == 200) {
          final data = jsonDecode(response.body);
          _token = data['token'];
          _currentUser = User.fromJson(data['user']);
          await _prefs.setString(_tokenKey, _token!);
          await _prefs.setString(_userKey, jsonEncode(data['user']));
          return true;
        }
        return false;
      } catch (e) {
        print('HTTP 请求失败: $e');
        return false;
      }
    } catch (e) {
      print('登录失败: $e');
      return false;
    }
  }

  Future<bool> register(String username, String email, String password) async {
    try {
      print('register');
      final response = await http.post(
        Uri.parse('$_baseUrl/register'),
        headers: {'Content-Type': 'application/json'},
        body: jsonEncode({
          'username': username,
          'email': email,
          'password': password,
        }),
      );

      if (response.statusCode == 201) {
        final data = jsonDecode(response.body);
        _token = data['token'];
        _currentUser = User.fromJson(data['user']);
        await _prefs.setString(_tokenKey, _token!);
        await _prefs.setString(_userKey, jsonEncode(data['user']));
        return true;
      }
      return false;
    } catch (e) {
      return false;
    }
  }

  Future<void> logout() async {
    _token = null;
    _currentUser = null;
    await _prefs.remove(_tokenKey);
    await _prefs.remove(_userKey);
  }
}
